<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>findFirstN</title>
</head>

<body>
    <div>打开浏览器控制台查看结果</div>
    <script>
        const findFirstN = (arr, matcher, n = 1) => {
            const res = [];
            for (const i in arr) {
                const el = arr[i];
                if (matcher(el, i, arr)) {
                    res.push(el);
                }
                if (res.length === n) {
                    return res;
                }
            }
            return res;
        };
        console.log(findFirstN([1, 2, 4, 6], n => n % 2 === 0, 2)); // [2, 4]
        console.log(findFirstN([1, 2, 4, 6], n => n % 2 === 0, 5)); // [2, 4, 6]
    </script>
</body>

</html>